package com.example.lowbird.lowbird.fragment;

import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.daimajia.slider.library.SliderLayout;
import com.example.lowbird.lowbird.R;
import com.example.lowbird.lowbird.adapter.CateAdapter;
import com.example.lowbird.lowbird.adapter.Myrvadapter;
import com.example.lowbird.lowbird.bean.CateRvbean;
import com.example.lowbird.lowbird.bean.CategorylvBean;
import com.example.lowbird.lowbird.bean.HotBean;
import com.example.lowbird.lowbird.constant.Contants;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * <p>
 * to handle interaction events.
 * Use the {@link CategoryFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CategoryFragment extends Fragment {

    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private SliderLayout mSl_category;

    private ListView lv_category;
    private int catid = 1;
    private int curPage = 1;
    private int catsize = 10;
    private CategorylvBean mLbean = null;
    private Context mContext;
    private List<CateRvbean.ListBean> list;
    private CateRvbean cateRvbean = null;
    List<CategorylvBean.DataBean> data;

    int flagcount = 0;
    boolean flag;
    private ArrayAdapter<String> sadapter;
    private List<String> lvarray = new ArrayList<>();
    private RecyclerView rv_cater;

    private CateAdapter cateAdapter;
    private CateRvbean bean;
    private MaterialRefreshLayout mrf_cat;
    private int totalpage = 0;
    private int pagesize = 10;

    public CategoryFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment CategoryFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static CategoryFragment newInstance(String param1, String param2) {
        CategoryFragment fragment = new CategoryFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        mContext = getContext();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_category, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
/**
 * 初始化一级listview，二级头部滚动条，以及二级recycleview
 */

        mrf_cat = ((MaterialRefreshLayout) view.findViewById(R.id.mrf_catfragment));
        mSl_category = ((SliderLayout) view.findViewById(R.id.sl_category));
        lv_category = ((ListView) view.findViewById(R.id.lv_category));
        sadapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, lvarray);
        lv_category.setAdapter(sadapter);


        intitclick();
        initlvdata();
        //调用hostFragment的静态方法添加mSl_category滚动数据
        Myrvadapter.initimages(mSl_category);

        rv_cater = ((RecyclerView) view.findViewById(R.id.rv_cater));
        cateAdapter = new CateAdapter(mContext, bean);

        rv_cater.setAdapter(cateAdapter);
        rv_cater.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        initrvata(curPage);
        setmrtfragment();


    }


    private void setmrtfragment() {
        //设置下拉刷新事件

        mrf_cat.setMaterialRefreshListener(
                new MaterialRefreshListener() {

                    @Override
                    public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {


                        if (cateRvbean == null) {
                            cateAdapter.clearhotbean();
                            curPage = 1;
                            totalpage = 0;
                            initrvata(curPage);

                            Log.e("CATM", "onRefresh: ");

                        } else {
                            cateAdapter.notifyDataSetChanged();
                            Log.e("CATM", "onRefresh: 2");
                            new Thread() {
                                @Override
                                public void run() {

                                    try {
                                        sleep(500);
                                        mrf_cat.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                mrf_cat.finishRefresh();

                                            }
                                        });
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }.start();
                        }
                    }

                    public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                        //上拉刷新...
                        Log.e("HOT", "onRefreshLoadMore: " + curPage + "total" + totalpage);
                        if (curPage < totalpage) {
                            curPage += 1;
                            initrvata(curPage);
                        } else {

                            Log.e("HOt", "已经是最后一页啦 ");
                            mrf_cat.finishRefreshLoadMore();

                        }

                    }
                });
        mrf_cat.setIsOverLay(false);
        mrf_cat.setWaveShow(true);


    }


    private void intitclick() {
        //左边listview添加监听事件
        lv_category.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//如果点击的item不是二级菜单的当前页，则进行跳转
                if (flagcount != position) {
                    curPage = 1;

                    catid = data.get(position).getId();
                    cateAdapter.clearhotbean();
                    initrvata(curPage);
                    totalpage = 0;
                    flagcount = position;
                }


            }


        });
    }


    private void initrvata(int curPage) {
//初始化recycleview数据源

        String url = Contants.API.WARES_LIST + "?curPage=" + curPage + "&pageSize=" + catsize + "&categoryId=" + catid;


        OkHttpUtils.get().url(url).build().execute(new StringCallback() {


            @Override
            public void inProgress(float progress, long total, int id) {


                super.inProgress(progress, total, id);
                Log.e("CATR", "progress :" + progress + ",total:" + total);
            }

            @Override
            public void onError(Call call, Exception e, int id) {

                mrf_cat.finishRefresh();
                mrf_cat.finishRefreshLoadMore();
            }

            @Override
            public void onResponse(String response, int id) {


                String s = response.toString();


                CateRvbean cateRvbean1 = new Gson().fromJson(s, CateRvbean.class);

                if (totalpage == 0) {

                    totalpage = cateRvbean1.getTotalCount() / pagesize + 1;
                }
                //通知适配器转换数据
                cateAdapter.addHotbean(cateRvbean1);

                //给当前catervbean刷新数据
                if (cateRvbean == null) {
                    cateRvbean = cateRvbean1;

                } else {

                    cateRvbean.getList().addAll(cateRvbean1.getList());
                }


                mrf_cat.finishRefresh();
                mrf_cat.finishRefreshLoadMore();


            }
        });

    }


    private void initlvdata() {

//初始化listview数据源
        OkHttpUtils.post().url(Contants.API.CATEGORY_LIST).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

                Log.e("CAT", "onError: " + e.toString());
            }

            @Override
            public void onResponse(String response, int id) {

                Log.e("CAT", "onResponse: " + id);
                String s = "{'data':" + response.toString() + "}";
                Log.e("CAT", "onResponse: " + s);
                mLbean = new Gson().fromJson(s, CategorylvBean.class);
                data = mLbean.getData();

                if (lvarray.size() < 1) {

                    for (int i = 0; i < data.size(); i++) {
                        lvarray.add(data.get(i).getName());

                    }
                    lv_category.post(new Runnable() {
                        @Override
                        public void run() {


                            sadapter.notifyDataSetChanged();
                        }
                    });
                }


            }
        });


    }


}
